/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Provides the column chart generation.
 * @author silvano.luciani@gmail.com (Silvano Luciani)
 */

var Adsense = Adsense || {};

/**
 * Class that generates the line chart.
 */
Adsense.Column = function() {};

/**
 * Sends a generate report request to the Management API and draws a column
 * chart to visualize the data.
 * @param {string} startDate Starting date for the report data.
 * @param {string} endDate Ending date for the report data.
 */
Adsense.Column.prototype.draw = function(startDate, endDate) {
  gapi.client.load('adsense', 'v1.2', function() {
    var request = gapi.client.adsense.reports.generate({
      'startDate': startDate,
      'endDate': endDate,
      'metric': ['PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS',
                 'INDIVIDUAL_AD_IMPRESSIONS'],
      'dimension': ['MONTH'],
      'sort': ['MONTH']
    });

    request.execute(function(resp) {
      var data = new google.visualization.arrayToDataTable(
          [['Month', 'PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS',
          'INDIVIDUAL_AD_IMPRESSIONS']].concat(resp.rows));
      var view = new google.visualization.DataView(data);
      view.setColumns([
        0, {
          calc: function(dataTable, rowNum) {
            return parseInt(dataTable.getValue(rowNum, 1))
          },
          type: 'number',
          label: 'Page views'
        },
        {
          calc: function(dataTable, rowNum) {
            return parseInt(dataTable.getValue(rowNum, 2))
          },
          type: 'number',
          label: 'Ad requests'
        },
        {
          calc: function(dataTable, rowNum) {
            return parseInt(dataTable.getValue(rowNum, 3))
          },
          type: 'number',
          label: 'Matched ad requests'
        },
        {
          calc: function(dataTable, rowNum) {
            return parseInt(dataTable.getValue(rowNum, 4))
          },
          type: 'number',
          label: 'Individual ad impressions'
        }
      ]);

      var wrapper = new google.visualization.ChartWrapper({
        chartType: 'ColumnChart',
        dataTable: view,
        options: {
          'title': 'Performances per month',
          'width': 700,
          'height': 300},
        containerId: 'column_chart_div'
      });
      wrapper.draw();
    });
  });
};
